<template>
    <div id="box">
        <input type="text" v-model="content" @keyup.enter="sent">
        <ul>
            <li v-for="(data, index) in datas" :key="data.id">
                <input type="checkbox" v-model="data.ischecked">
                <span :class="data.ischecked ? 'text' : ''">{{ data.content }}</span>
                <button @click="del(index)">删除</button>
            </li>
        </ul>
        <div id="footer">
            <input type="checkbox" v-model="checkedAll">
            <span>{{ numberSelect }}</span>
            <span>{{ this.datas.length }}</span>
            <span @click="delAll">清除已完成任务</span>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                // 输入框的内容
                content: '',
                // 数据库
                datas: []
            }
        },
        methods: {
            // 回车添加待办事项
            sent(){
                this.datas.push({id: Date.now(), ischecked: false, content:this.content})
                this.content = ''              
            },
            // 删除单个待办事项
            del(index){
                if(this.datas[index].ischecked === true){
                    this.datas.splice(index, 1)
                }
            },
            // 删除已完成的待办事项
            delAll(){
                let newDatas = this.datas.filter((data) => !data.ischecked)
                this.datas = newDatas
            }
        },
        computed: {
            // 全选框
            checkedAll: {
                get(){
                    return this.datas.every((data) => data.ischecked)
                },
                set(status){
                    this.datas.forEach((data) => {
                        data.ischecked = status
                    })
                }
            },
            // 计算已完成的待办事项的数量
            numberSelect(){
                return this.datas.filter((data) => data.ischecked).length
            }
        },
        watch: {
            // 监听datas的数据变化，将数据存入本地存储
            datas: {
                handler(newV, oldV){
                    localStorage.setItem('comments', JSON.stringify(newV))
                },
                deep: true,
            }
        },
        // 挂载后将本地存储的数据渲染到页面上
        mounted() {
            let comment = JSON.parse(localStorage.getItem('comments'))
            this.datas = comment
        }
    }
</script>

<style lang="scss" scoped>
* {
    margin: 0;
    padding: 0;
    list-style-type: none;
    box-sizing: border-box;
}
#box {
    width: 172px;
}
ul li, #footer {
    display: flex;
    justify-content: space-between;
}
.text {
    color: #ccc;
    text-decoration: line-through;
}
</style>